package com.dycx.api.controller.app.user;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dycx.common.RestResponse;
import com.dycx.common.ValidationGroup;
import com.dycx.common.annotation.Authorization;
import com.dycx.common.context.UserInfoContext;
import com.dycx.user.dto.SellerDTO;
import com.dycx.user.dto.UserDTO;
import com.dycx.user.dto.WithdrawDepositDTO;
import com.dycx.user.entity.UserDO;
import com.dycx.user.enums.AgencyGradeEnum;
import com.dycx.user.enums.TransactionTypeEnum;
import com.dycx.user.mapper.WalletLogMapper;
import com.dycx.user.service.QrCodeService;
import com.dycx.user.service.SellerService;
import com.dycx.user.service.UserService;
import com.dycx.user.service.WithdrawDepositService;
import com.dycx.user.vo.SellerVO;
import com.dycx.user.vo.UserVO;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@RequestMapping(value = "/app/user/user")
@AllArgsConstructor
public class UserApiController {
    private UserService userService;
    private SellerService sellerService;
    private QrCodeService qrCodeService;
    private WalletLogMapper walletLogMapper;
    private WithdrawDepositService withdrawDepositService;

    /**
     * 获取用户信息
     *
     * @return
     */
    @Authorization
    @GetMapping("getTokenInfo")
    public RestResponse<UserVO> getTokenInfo() {
        return RestResponse.success(userService.load(UserInfoContext.get().getUserId()));
    }

    @Authorization
    @PostMapping("getPage")
    public RestResponse<Page<UserVO>> getPage(@RequestBody UserDTO dto) {
        dto.setShareUid(UserInfoContext.get().getUserId());

        Boolean team = "team".equals(dto.getQueryType());
        Boolean agency = "agency".equals(dto.getQueryType());

        Page<UserVO> page = userService.getPage(dto);
        System.out.println("==================================================");
        if (team || agency) {
            page.getRecords().forEach(item -> {
                //团队人数
                LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(UserDO::getShareUid, item.getUid());
                wrapper.and(o -> {
                    o.gt(UserDO::getVipGrade, 0)
                            .or()
                            .gt(UserDO::getAgencyGrade, 0);
                });
                item.setTeamUserNum(userService.count(wrapper) + 1);

                //团队金额
                LambdaQueryWrapper<UserDO> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(UserDO::getShareUid, item.getUid());
                wrapper2.gt(UserDO::getVipGrade,0);
                List<UserDO> userList = userService.list(wrapper2);
                List<Integer> uids = userList.stream().map(UserDO::getUid).collect(Collectors.toList());
                uids.add(item.getUid());
                Integer teamMoney = walletLogMapper.calcTotal(uids, TransactionTypeEnum.RECHARGE_AMOUNT.getCode());
                item.setTeamUserMoney(teamMoney);
            });
        }


        return RestResponse.success(page);
    }

    /**
     * 修改密码
     **/
    @Authorization
    @PostMapping("/updatePassword")
    public RestResponse<Boolean> updatePassword(@RequestBody @Validated(ValidationGroup.UpdatePassword.class) UserDTO dto) {
        dto.setUid(UserInfoContext.get().getUserId());
        return userService.updatePassword(dto) ? RestResponse.success() : RestResponse.fail();
    }

    /**
     * 修改手机号
     **/
    @Authorization
    @PostMapping("/updateMobile")
    public RestResponse<Boolean> updateMobile(@RequestBody @Validated(ValidationGroup.MobileCode.class) UserDTO dto) {
        dto.setUid(UserInfoContext.get().getUserId());
        return userService.updateMobile(dto) ? RestResponse.success() : RestResponse.fail();
    }

    /**
     * 修改个人信息
     **/
    @Authorization
    @PostMapping("/updateInfo")
    public RestResponse<Boolean> updateInfo(@RequestBody UserDTO userDTO) {
        userDTO.setUid(UserInfoContext.get().getUserId());
        return userService.update(userDTO) ? RestResponse.success() : RestResponse.fail();
    }

    /**
     * 提交商家审核
     **/
    @Authorization
    @PostMapping("/sellerApply")
    public RestResponse<Boolean> sellerApply(@RequestBody @Valid SellerDTO sellerDto) {
        return sellerService.sellerApply(sellerDto) ? RestResponse.success() : RestResponse.fail();
    }

    @Authorization
    @GetMapping("/getSellerInfo")
    public RestResponse<SellerVO> getSellerInfo() {
        return RestResponse.success(sellerService.getSellerInfoByUid(UserInfoContext.get().getUserId()));
    }

    @Authorization
    @GetMapping("/getQrcode")
    public RestResponse<String> getQrcode() {
        return RestResponse.success(qrCodeService.getQrcode(UserInfoContext.get().getUserId()));
    }

    /**
     * 统计团队数据
     *
     * @return
     */
    @Authorization
    @GetMapping("/statisticsTeamData")
    public RestResponse<Map<String, Integer>> statisticsTeamData() {
        return RestResponse.success(userService.statisticsTeamData(UserInfoContext.get().getUserId()));
    }

    /**
     * 统计团队数据
     *
     * @return
     */
    @Authorization
    @PostMapping("/withdrawDepositApply")
    public RestResponse<Boolean> withdrawDepositApply(@RequestBody @Validated(ValidationGroup.Insert.class) WithdrawDepositDTO dto) {
        dto.setUid(UserInfoContext.get().getUserId());
        return RestResponse.success(withdrawDepositService.create(dto));
    }

    /**
     * 设为代理
     **/
    @Authorization
    @GetMapping("/setAgency")
    public RestResponse<Boolean> setAgency(Integer uid) {
        UserVO userVO = userService.load(UserInfoContext.get().getUserId());
        if (ObjectUtil.isNull(userVO.getAdminId()) || userVO.getAdminId() < 1) {
            return RestResponse.fail("没有操作权限");
        }

        UserDO userDO = new UserDO();
        userDO.setUid(uid);
        userDO.setAgencyGrade(AgencyGradeEnum.GOLD.getCode());
        if(!userService.updateById(userDO)) return RestResponse.fail();

        return RestResponse.success();
    }

    /**
     * 取消代理代理
     **/
    @Authorization
    @GetMapping("/cancelAgency")
    public RestResponse<Boolean> cancelAgency(Integer uid) {
        UserVO userVO = userService.load(UserInfoContext.get().getUserId());
        if (ObjectUtil.isNull(userVO.getAdminId()) || userVO.getAdminId() < 1) {
            return RestResponse.fail("没有操作权限");
        }

        UserDO userDO = new UserDO();
        userDO.setUid(uid);
        userDO.setAgencyGrade(AgencyGradeEnum.NO.getCode());
        if(!userService.updateById(userDO)) return RestResponse.fail();

        return RestResponse.success();
    }

    @Authorization
    @PostMapping("/getPageByAll")
    public RestResponse<Page<UserVO>> getPageByAll(@RequestBody UserDTO dto) {
        UserVO userVO = userService.load(UserInfoContext.get().getUserId());
        if (ObjectUtil.isNull(userVO.getAdminId()) || userVO.getAdminId() < 1) {
            return RestResponse.fail("没有操作权限");
        }

        Page<UserVO> page = userService.getPage(dto);

        return RestResponse.success(page);
    }
}
